package com.rongmei.jdsync.util;

import com.rongmei.jdsync.entity.JdSyncLog;
import com.rongmei.jdsync.entity.enums.OperationType;
import com.rongmei.jdsync.repository.JdSyncLogRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@RequiredArgsConstructor
public class SyncLogUtils {

    private final JdSyncLogRepository logRepository;
    private final HttpServletRequest request;

    public JdSyncLog startLog(Long goodsId, Long skuId, OperationType operationType, String operator) {
        JdSyncLog log = new JdSyncLog();
        log.setGoodsId(goodsId);
        log.setSkuId(skuId);
        log.setOperationType(operationType);
        log.setOperator(operator);
        log.setIpAddress(getClientIp());
        return logRepository.save(log);
    }

    public void successLog(JdSyncLog log, String responseData) {
        log.setStatus("SUCCESS");
        log.setResponseData(responseData);
        log.setExecutionTime(log.calculateExecutionTime());
        logRepository.save(log);
    }

    public void failLog(JdSyncLog log, Exception e) {
        log.setStatus("FAILED");
        log.setErrorMessage(e.getMessage());
        log.setStackTrace(getStackTrace(e));
        log.setExecutionTime(log.calculateExecutionTime());
        logRepository.save(log);
    }

    private String getStackTrace(Exception e) {
        StringBuilder sb = new StringBuilder();
        for (StackTraceElement element : e.getStackTrace()) {
            sb.append(element.toString()).append("\n");
        }
        return sb.toString();
    }

    private String getClientIp() {
        try {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        } catch (IllegalStateException e) {
            // 非Web请求环境，返回默认IP
            return "127.0.0.1";
        }
    }
}
